
close all
clear all
clc

gavgdir = '/home/predatt/anatod/ISI/MEG/GAVG';
cd(gavgdir)
load subjname
load dataset
load ChanSel % load sensor selection

rootdir = '/home/predatt/anatod/ISI';
datadir = '/home/predatt/anatod/ISI/raw'; 

    cond{1} = 't3: focal_1st';      		cond_trig{1} = [33]; 
    cond{2} = 't3: focal_2nd';     			cond_trig{2} = [34]; 
    cond{3} = 't3: distributed_1st';        cond_trig{3} = [35]; 
    cond{4} = 't3: distributed_2nd';        cond_trig{4} = [36];

for sb=1:24
    
    

    clear tfr_hi tfr_lo tfr_high tfr_low;
    fprintf('Loading subject %s... \n', subjname{sb});
    subdir = fullfile(rootdir,'MEG',subjname{sb});
    cd(subdir) 

      filename = strcat(subjname{sb},'_TFR_lo');
    load(filename);
    
      clear trial_indx
    for i=1:length(cond) 
      trial_indx{i} = [];
        for j=1:length(tfr_lo.trialinfo)
            if sum(tfr_lo.trialinfo(j,1)==cond_trig{i})
                trial_indx{i}(end+1)=j;
            end
        end
    end
        
       
       
    
% convert to decibel scale    
        tfr_lo.powspctrm = 10*log10(tfr_lo.powspctrm);

% select trials per condition

cfg.trials = []; cfg.trials = trial_indx{1};
tfr_low{1} = ft_selectdata(cfg,tfr_lo);
cfg.trials = []; cfg.trials = trial_indx{2};
tfr_low{2} = ft_selectdata(cfg,tfr_lo);
cfg.trials = []; cfg.trials = trial_indx{3};
tfr_low{3} = ft_selectdata(cfg,tfr_lo);
cfg.trials = [];  cfg.trials = trial_indx{4};
tfr_low{4} = ft_selectdata(cfg,tfr_lo);
 
    % make frequency description of each condition
 
        for i = 1:length(cond)
        
        cfg = [];
        cfg.variance      = 'no';
        cfg.jackknife     = 'no';
        cfg.keeptrials    = 'no';
        cfg.trials        = 'all';
        cfg.foilim        = 'all';
        cfg.toilim        = 'all';

        savg_lo_avg{i}{sb} = my_freqdescriptives(cfg,tfr_low{i}); % take median
        end
end

cd(gavgdir)
save savg_TFR_TONES_nobaseline savg_lo_avg 

% take baseline
for i=1:length(cond)
    for sb=1:length(subjname)
            cfg.baseline     = [-0.5 -0.4];
            cfg.baselinetype = 'absolute'; 
            savg_lo_avg{i}{sb} = ft_freqbaseline(cfg, savg_lo_avg{i}{sb});
    end
end

% frequency grand average per condition, for stats
cfg = [];
cfg.keepindividual = 'yes';
cfg.foilim         = 'all';
cfg.toilim         = 'all';
cfg.channel        = 'MEG';

for i=1:length(cond)
    gavg_lo{i} = ft_freqgrandaverage(cfg,savg_lo_avg{i}{1:length(subjname)});
end
save gavg_TFRs_TONES gavg_lo;
 
 % average everything for plotting
cfg.keepindividual = 'no';
gavg_hi_all = ft_freqgrandaverage(cfg, gavg_hi{1:4});
gavg_lo_all = ft_freqgrandaverage(cfg, gavg_lo{1:4});

save gavg_TFRs_TONES_all gavg_hi_all gavg_lo_all;


